<?php

class Osml_Acl extends Jnd_Acl
{

    public function __construct ()
    {
        // Déclaration des roles de l'application.
        $model = new Back_Model_Roles();
        $roles = $model->lister();
        $this->addRole(new Zend_Acl_Role("invite"));
        foreach ($roles as $role) {
            if ($role->getNom() != "invite") {
                $this->addRole(new Zend_Acl_Role($role->getNom()), "invite");
            }
        }
        
        // Déclaration des ressources
        $model = new Back_Model_Ressources();
        $ressources = $model->lister();
        foreach ($ressources as $ressource) {
            $tmp = $ressource->getModule() . "." . $ressource->getNom();
            $this->add(new Zend_Acl_Resource($tmp));
            if ($ressource->getModule() == "back") {
                $this->deny("invite", $tmp);
                $this->allow("admin");
            }
        }
        
        // Appplication de la LCA
        $model = new Back_Model_Droits();
        $droits = $model->lister();
        foreach ($droits as $droit) {
            $ressource = $droit->getRessource();
            $autorise = (bool) $droit->getAutorise();
            $action = $droit->getAction();
            $action = ($action == "*" ? '' : $action);
            $role = Back_Model_Roles::recuperationValeurParId(
                    $droit->getIdRole());
            if ($autorise) {
                $methode = "allow";
            } else {
                $methode = "deny";
            }
            if ($action != "") {
                $this->$methode($role, $ressource, $action);
//                 echo "Méthode avec Privilège '$methode' pour $role - $ressource - $action<br />";
//                 Zend_Debug::dump(array("Sans Privilège" => $this->isAllowed("invite", $ressource, null)));
            } else {
                $this->$methode($role, $ressource, null);
//                 echo "Méthode sans Privilège '$methode' pour $role - $ressource <br />";
//                 Zend_Debug::dump($this->isAllowed($role, $ressource));
            }
        }
        
        Zend_Registry::set("acl", $this);
        
//         Zend_Debug::dump($this->_rules["byResourceId"]["front.index"]['byRoleId']['invite']);
    }
    
    public function isAllowedArray(array $roles, $ressource, $privilege = null) {
        $flag = false;
        foreach( $roles as $role) {
            $roleTexte = Back_Model_Roles::recuperationValeurParId($role);
            $flag = $this->isAllowed($roleTexte, $ressource, $privilege);
            if( $flag ) {
                return true;
            }
        }
        return $flag;
    }
   
}
